package com.tomek.ktoryoperator.tasks;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentResolver;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;

import com.tomek.ktoryoperator.R;
import com.tomek.ktoryoperator.adapters.MainListAdapter;
import com.tomek.ktoryoperator.model.DBEntry;
import com.tomek.ktoryoperator.model.EntryState;
import com.tomek.ktoryoperator.model.SingleEntry;
import com.tomek.ktoryoperator.utils.ContentProvidersUtils;

public class UpdateListAdapterTask extends AsyncTask<Void, Void, Boolean> {

	final ContentResolver contentResolver;
	final MainListAdapter adapter;
	final long updateTime;
	final Context context;

	public UpdateListAdapterTask(Context context, ContentResolver contentResolver, MainListAdapter adapter,
			long updateTime) {
		this.contentResolver = contentResolver;
		this.adapter = adapter;
		this.updateTime = updateTime;
		this.context = context;
	}

	@Override
	protected Boolean doInBackground(Void... params) {
		ArrayList<DBEntry> entries = ContentProvidersUtils.getNewEntries(contentResolver, updateTime);
		List<SingleEntry> listEntries = adapter.getAllItems();

		boolean anyChanges = false;

		for (DBEntry dbEntry : entries) {
			for (SingleEntry listEntry : listEntries) {

				if (dbEntry.number.equals(listEntry.number)) {
					listEntry.date = dbEntry.date;

					if (!dbEntry.value.equals(listEntry.valueId)) {
						listEntry.valueId = dbEntry.value;
						listEntry.providerId = dbEntry.provider;
						listEntry.state = EntryState.UPDATED;

						anyChanges = true;
					}
				}
			}
		}

		return anyChanges;
	}

	@Override
	protected void onPostExecute(Boolean anyChanges) {
		if (anyChanges) {
			adapter.notifyDataSetChanged();
		} else {
			Toast.makeText(context, R.string.no_change, Toast.LENGTH_LONG).show();
		}
	}
}